import {
	getTodayDateString,
	kAppToken,
	kAppKey
} from '../utils/common.js'

import CryptoJS from '../utils/cryptojs.js'

// const iv = CryptoJS.enc.Utf8.parse(kAppKey);
const iv = CryptoJS.enc.Utf8.parse("");
// 导入云对象
const appManager = uniCloud.importObject('appManager');
const db = uniCloud.database();
export function getUserScore() {
	try {
		const startScore = 1000;
		const value = uni.getStorageSync('myScore');
		if (value && value >= 0) {
			return value;
		} else {
			uni.setStorageSync('myScore', '' + startScore);
			return startScore;
		}
	} catch (e) {
		// error
		return startScore;
	}
}

// 本地数据
export function addUserScore(score) {
	try {
		let value = uni.getStorageSync('myScore');
		let sum = Number(value) + score;
		if (sum < 0) {
			// uni.setStorageSync('myScore', 0);
			uni.showToast({
				title: '积分不够了',
				icon: "none",
				duration: 1500
			})
			return -1;
		} else {
			uni.setStorageSync('myScore', '' + sum);
			return sum;
		}
	} catch (e) {
		// error
		uni.showToast({
			title: '数据异常，请稍后再试',
			icon: "none",
			duration: 1500
		})
		return -1;
	}
}

export function saveUserCloudScoreToLocal(score) {
	uni.setStorageSync("CloudScore", score);
	return getTotalUserScore();
}

// 保存用户增加分数
// type  1是签到 其他是itemtype
// 2 幸运777 3 喜相逢 4好运来
export function saveUserAddScoreToLocal(score, type, gameid, gamename) {
	const total = getTotalUserScore();
	const sum = total + score;
	if (sum < 0) {
		uni.showToast({
			title: '金币不够了,可以点击金币按钮获取更多金币！',
			icon: "none",
			duration: 1500
		})
	} else {
		const current = uni.getStorageSync('AddScore');
		if (current) {
			const addScore = score + current;
			uni.setStorageSync("AddScore", addScore);
		} else {
			uni.setStorageSync("AddScore", score);
		}

		const userid = uni.getStorageSync("userid")
		if (userid && score > 0) {
			const userScore = {
				"userid": userid,
				"gameid": gameid,
				"gamename": gamename,
				"addscore": Number(score),
				"scoretype": Number(type),
				"datetime": new Date().getTime(),
				"datetimeStr": getTodayDateString()
			}
			
			const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(userScore), kAppToken, {
				iv: iv, // 使用上面定义的IV
				mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
				padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
			}).toString();
			
			console.log("添加用户得分记录data: " + encryptedData);
			appManager.addUserScoreHistory({
				data: encryptedData
			}).then(res=>{
				console.log("添加用户得分记录res: " + JSON.stringify(res));
			})
		}
	}

	return getTotalUserScore();
}

// 获取用户分数
export function getTotalUserScore() {
	const current = uni.getStorageSync('AddScore');
	const currentCloud = uni.getStorageSync('CloudScore');
	const currentScore = Number(current);
	const currentCloudScore = Number(currentCloud);
	if (currentScore && currentCloudScore) {
		return currentScore + currentCloudScore;
	} else {
		if (currentScore) {
			return currentScore;
		} else if (currentCloudScore) {
			return currentCloudScore;
		}
		return 0;
	}
}

// 保存用户分数到云平台
export async function saveUserTotalScoreToCloud() {
	const db = uniCloud.database();
	// 获取当前增加的分数
	const currentScore = uni.getStorageSync('AddScore');
	const openid = uni.getStorageSync("UserOpenId");
	if (currentScore == 0) {
		return;
	}
	try {
		// 首次进入 加载用户信息
		const username = uni.getStorageSync("UserOpenId");
		// 导入云对象
		// 使用AES算法、CBC模式和PKCS#7填充对明文进行加密
		const encryptedData = CryptoJS.AES.encrypt(username, kAppToken, {
			iv: iv, // 使用上面定义的IV
			mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
			padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
		}).toString();
		// 调用云对象方法
		console.log(username+'，'+encryptedData);
		appManager.getUserInfo({
			data: encryptedData
		}).then(res => {
			// const decryptedData = CryptoJS.AES.decrypt(res.data, kAppToken, {
			// 	iv: iv, // 使用上面定义的IV
			// 	mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
			// 	padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
			// }).toString(CryptoJS.enc.Utf8);
			// const body = JSON.parse(decryptedData);
			const user = res.data[0];
			console.log("saveUserTotalScoreToCloudgetUserInfo: " + JSON.stringify(res));
			// const user = res.data[0];
			// 总分
			const total = user.score + currentScore;
			// 今日总分
			let todayscore = user.todayscore;
			// 今天日期
			let todayscoredate = user.todayscoredate;
			// 判断是否是同一天数据 如果是累加
			if (user.todayscoredate === getTodayDateString()) {
				todayscore = todayscore + currentScore;
			} else {
				// 如果不是直接赋值
				todayscoredate = getTodayDateString();
				todayscore = currentScore;
			}
			let datetime = new Date().getTime() 
			let userid = uni.getStorageSync('userid');
			if(!userid) return;
			const updateInfo = {
				score: total,
				todayscore,
				todayscoredate,
				username,
				datetime,
				userid
			}
			// 使用AES算法、CBC模式和PKCS#7填充对明文进行加密
			const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(updateInfo), kAppToken, {
				iv: iv, // 使用上面定义的IV
				mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
				padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
			}).toString();
			console.log("更新用户数据", encryptedData	);
			appManager.updateUserInfo({
				data: encryptedData
			}).then(res => {
				console.log("更新用户数据", JSON.stringify(res));
				if (res.errCode == 0) {
					// 清空本地今天数据
					uni.setStorageSync("AddScore", 0);
					// 保存今天总数据
					saveUserCloudScoreToLocal(total);
				}
			})
		}).catch(e => {
			console.log("saveUserTotalScoreToCloudgetUserInfo: " + JSON.stringify(e));
		});
	} catch (e) {
		console.log("保存用户分数到Cloudy异常", e);
	}

}

// 保存用户分数到云平台
export async function saveUserTotalScoreToCloudOld() {
	const db = uniCloud.database();
	// 获取当前增加的分数
	const currentScore = uni.getStorageSync('AddScore');
	const openid = uni.getStorageSync("UserOpenId");
	const query = db.collection("open_user").where({
		username: openid
	});
	if (currentScore == 0) {
		return;
	}
	try {
		const res = await query.field('score as score,todayscore,todayscoredate').get();
		if (res.result.data && res.result.data.length) {
			// 总分
			const total = res.result.data[0].score + currentScore;
			// 今日总分
			let todayscore = res.result.data[0].todayscore;
			// 今天日期
			let todayscoredate = res.result.data[0].todayscoredate;
			// 判断是否是同一天数据 如果是累加
			if (res.result.data[0].todayscoredate === getTodayDateString()) {
				todayscore = todayscore + currentScore;
			} else {
				// 如果不是直接赋值
				todayscoredate = getTodayDateString();
				todayscore = currentScore;
			}
			await query.update({
				score: total,
				todayscore,
				todayscoredate
			})

			// 清空本地今天数据
			uni.setStorageSync("AddScore", 0);
			// 保存今天总数据
			saveUserCloudScoreToLocal(total);
		}
	} catch (e) {
		console.log("保存用户分数到Cloudy异常", e);
	}

}

// 获取用户云储存分数
export async function getUserScoreFromCloud() {
	try {
		const openid = uni.getStorageSync("UserOpenId");
		const userInfo = await db.collection("open_user").where({
			username: openid
		}).field('_id,score as score,avatar,nickname,updateuserdate,register_date').get();
		if (userInfo && userInfo.result.data) {
			uni.setStorageSync("userid", userInfo.result.data[0]._id)
			uni.setStorageSync("registerdate", userInfo.result.data[0].register_date)
			return userInfo.result.data[0];
		}
	} catch (e) {
		console.log("getUserScoreCloud error:" + e);
		return -1;
	}
}

// 签到分数
export function SignInGetScore() {
	let today = getTodayDateString()
	try {
		uni.showToast({
			title: '获取100金币成功',
			icon: "success",
			duration: 1500
		})
		uni.setStorageSync('SignIn', today)
		const value = uni.getStorageSync('AddScore');
		if (value) {
			uni.setStorageSync('AddScore', Number(value) + 1000)
		} else {
			uni.setStorageSync('AddScore', 1000);
		}
		return getTotalUserScore();
	} catch (e) {
		// error
		return getTotalUserScore();
	}
}


// 签到分数
export function SignInGetScoreLocal() {

	let today = getTodayDateString()
	try {
		const value = uni.getStorageSync('SignIn');
		if (value === today) {
			uni.showToast({
				title: '已签到，明天再来试试吧',
				icon: "none",
				duration: 1500
			})
			return getUserScore();
		} else {
			uni.showToast({
				title: '签到成功',
				icon: "success",
				duration: 1500
			})
			uni.setStorageSync('SignIn', today)
			const value = uni.getStorageSync('myScore');
			if (value && value > 0) {
				uni.setStorageSync('myScore', Number(value) + 200)
			} else {
				uni.setStorageSync('myScore', 200);
			}
		}
		return getUserScore();
	} catch (e) {
		// error
		return getUserScore();
	}
}